/**
 * CS543 HW4 Joseph Meyer
 */
package edu.src.hardware;

import java.util.ArrayList;
import java.util.List;

import edu.src.paging.PageTable;

/**
 * Similar to the Backing frame<br>
 * This supports the Physical Memory to simulate page / addressing.
 * The size of this frame is determined by <code>PageTable.TABLE_SIZE</code>
 * 
 * @author meyer
 *
 */
public class PhysicalMemoryFrame {

	/**
	 * Holds the loaded bytes of this fram
	 */
	private List<ByteEntry> dataList;
	
	/**
	 * Default constructor
	 */
	public PhysicalMemoryFrame() {
		dataList = new ArrayList<>(PageTable.TABLE_SIZE);
		for (int i = 0; i < PageTable.TABLE_SIZE; i++) {
			dataList.add(null);
		}
	}
	
	/**
	 * @param b - Byte
	 * @param offset - the index / offset
	 */
	public void addToList(Byte b, int offset) {
		ByteEntry be = new ByteEntry(b);
		dataList.add(offset, be);
	}
	
	/**
	 * @param offset
	 */
	public Byte getFromList(int offset) {
		ByteEntry be = dataList.get(offset);
		if (be != null) {
			return be.getValue();
		}
		return null;
	}
	
	/**
	 * @return ByteEntry - the oldest entry this frame contains
	 */
	public ByteEntry getOldestEntry() {
		ByteEntry oldest = null;
		long oldestTime = Long.MAX_VALUE;
		int index = 0;
		for (ByteEntry be : dataList) {
			if (be != null) {
				if (be.getTimestamp() < oldestTime) {
					oldestTime = be.getTimestamp();
					oldest = be;
					oldest.setIndex(index);
				}
			}
			index++;
		}
		//might be null;
		return oldest;
	}

}
